package com.anti.modular.sys.auth.controller;

import cn.hutool.core.convert.Convert;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.commom.api.Result;
import com.anti.commom.constant.CommonConstant;
import com.anti.commom.context.constant.ConstantContextHolder;
import com.anti.commom.core.exception.AuthException;
import com.anti.commom.core.exception.enums.AuthExceptionEnum;
import com.anti.commom.core.utils.HttpServletUtil;
import com.anti.commom.core.utils.StringUtils;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.core.security.service.AuthService;
import com.anti.modular.sys.auth.param.LoginInfoParam;
import com.anti.modular.sys.auth.pojo.SysLoginUser;
import com.wf.captcha.SpecCaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description TODO
 * @Author anTi
 * @Date 2021-2-24
 */
@Controller
public class SysLoginController {
    @Resource
    private AuthService authService;

    @RequestMapping("/refreshCode")
    @ResponseBody
    public Result refreshCode(){
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        String verCode = specCaptcha.text().toLowerCase();
        String verKey =  IdUtil.simpleUUID();
        String captchaToken= CommonConstant.VERIFICATION_CODE_PREFIX+verKey;        // 存入redis并设置过期时间
        HttpServletUtil.getRequest().getSession().setAttribute(captchaToken,verCode);
//        redisService.setExpire(s, verCode, 20, TimeUnit.MINUTES);
        // 将key和base64返回给前端
        Map<String,Object> res=new HashMap<String, Object>();
        res.put("key",verKey);
        res.put("image",specCaptcha.toBase64());
        return Result.data(res);
    }

    @RequestMapping("/validateCode")
    @ResponseBody
    public boolean validateCode(HttpServletRequest request){
        String checkCode = request.getParameter("checkCode");
        String verKey=request.getParameter("verKey");
        String captchaToken= CommonConstant.VERIFICATION_CODE_PREFIX+verKey;
//        String v_captcha = (String) redisService.get(captchaToken);
        String v_captcha = "";
        if (StringUtils.isBlank(v_captcha)){
            return false;
        }
        if (!checkCode.equalsIgnoreCase(v_captcha)) {
            return false;
        }
        return true;
    }

    /**
     * 账号密码登录接口，POST请求
     */
    @ResponseBody
    @PostMapping("/login")
    public Result login(@RequestBody LoginInfoParam loginInfoParam) {
        String account = loginInfoParam.getAccount();
        String password = loginInfoParam.getPassword();
        String verKey = loginInfoParam.getVerKey();
        String captcha = loginInfoParam.getCheckCode();
        //如果开启了验证码，则先校验验证码
        if (ConstantContextHolder.getCaptchaFlag()) {
            String captchaToken= CommonConstant.VERIFICATION_CODE_PREFIX+verKey;
            String sessionCaptcha = Convert.toStr(HttpServletUtil.getRequest().getSession().getAttribute(captchaToken));
            if (ObjectUtil.isEmpty(captcha) || !captcha.equalsIgnoreCase(sessionCaptcha)) {
                throw new AuthException(AuthExceptionEnum.VALID_CODE_ERROR);
            }
        }
        String token = authService.login(account, password);
        return  Result.data(token);
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    @ResponseBody
    public void logout() {
        authService.logout();
    }

    /**
     * 获取验证码开关
     */
    @GetMapping("/getCaptchaOpen")
    @ResponseBody
    public Result getCaptchaOpen() {
        return Result.data(ConstantContextHolder.getCaptchaOpenFlag());
    }

    /**
     * 获取当前登录用户信息
     */
    @ResponseBody
    @RequestMapping ("/getLoginUser")
    public Result getLoginUser() {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUserUpToDate();
        return Result.data(sysLoginUser);
    }

}
